<?php
namespace console\controllers;


use common\models\ActiveAttr;
//use common\models\ActivityAttr;
use common\models\Group;
use common\models\MoneyChange;
use common\models\Order;
use common\models\Shop;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\RedisServer;
use common\service\WechatService;
use yii\console\Controller;

class OrderController extends Controller
{

    public function actionTest(){
        $this->stdout('1#');
    }

    /**
     * php yii order/auto-receipt
     * 确认自动收货
     */
    public function actionAutoReceipt(){
        $order_querey = Order::find();
        $order_querey->andWhere(['order_status'=>ConstantService::$order_status['WAIT_RECEIPT']]);
        $order_querey->andWhere(['<= ','defaults_time',time()]);
        $order = $order_querey->asArray()->all();
        if(!empty($order)){
            $order_ids = array_column($order,'id');
            $re = Order::updateAll(['order_status'=>ConstantService::$order_status['SUCCESS']],['id'=>$order_ids]);

            $orders = Order::find()->where(['id'=>$order_ids])->asArray()->all();
            foreach ($orders as $order){
                //添加商户余额
                $shop = Shop::findOne(['id' => $order['shop_id']]);
                //商户余额
                $money = sprintf("%.2f",$shop['shop_money']) + sprintf("%.2f",$order['order_money']);
                $before_money = MoneyChange::find()
                    ->where(['shop_id'=>$order['shop_id']])
                    ->orderBy(['id'=>SORT_DESC])
                    ->one();
                $before_money = !empty($before_money) ? $before_money['after_money'] :'0.00';
                $change_model = new MoneyChange();
                $data['money'] = sprintf("%.2f",$order['order_money']);
                $data['after_money'] = sprintf("%.2f",$money);
                $data['before_money'] = sprintf("%.2f",$before_money);
                $data['shop_id'] = $order['shop_id'];
                $data['remark'] = '订单流入';
                $data['type'] = 0;
                $data['create_time'] = time();
                $change_model->setAttributes($data);
                $change_model->save();

                $shop->shop_money = sprintf("%.2f",$money);
                $shop->save();

                //添加销量 goods_attr_id
                $current_goods_attr = ActiveAttr::findOne(['id'=>$order['goods_attr_id']]);
                $current_goods_attr->sales_volume = $current_goods_attr['sales_volume']+1;
                $current_goods_attr->save();
            }
        }
        return true;
    }

    /**
     * php yii order/auto-expire
     * 修改验证成团是否有效 使用定时任务
     */
    public function actionAutoExpire(){
        //定时任务检查   被动触发 前端每次请求需要判断
        $group_model = Group::find();
        $group_model->andWhere(['status'=>2]);
        $group_model->andWhere(['<=','expire_time',time()]);

        $group = $group_model->asArray()->all();
        if(!$group){
           return true;
        }
        $group_ids = array_column($group,'id');

        $re = Group::updateAll(['status'=>1,'complete_time'=>time()],['id'=>$group_ids]);
        //修改订单状态
        Order::updateAll(['order_status'=>ConstantService::$order_status['WAIT_DELIVER']],['group_id'=>$group_ids]);
        return true;

    }


    /**
     * php yii order/auto-close-order
     * 超时未支付自动关闭
     */
    public function actionAutoCloseOrder(){
            $time = time()-15*60;
            $order_model = Order::find();
            $order_model->andWhere(['pay_status' => ConstantService::$pay_status['WAIT_PAY']]);
            $order_model->andWhere(['<=','created_time',$time]);
            $order_model->andWhere(['order_status' => ConstantService::$order_status['PAY_WAIT']]);
            $order_model->andWhere(['is_delete' => 0]);
            $orders =$order_model->asArray()->all();
            if(empty($orders)){
                return true;
            }
            $id = array_column($orders,'id');
            $re = Order::updateAll(['order_status'=>ConstantService::$order_status['CLOSED'],'pay_status'=>ConstantService::$pay_status['PAY_FAIL']],['id'=>$id]);

            //修改redis
            foreach ($orders as $val){
                $key = 'goods_'.$val['goods_attr_id'];
                $value = RedisServer::initialization()->getRedis($key);
                if(!empty($value)){
                    $value +=$val['goods_num'];
                    RedisServer::initialization()->addRedis($key,$value);
                }
            }
        return true;
    }

    /**
     * php yii order/order-refund
     * 退款超过2小时未处理自动退款
     */
    public function actionOrderRefund(){
        $time = time()-2*60*60;
        $order_model = Order::find()
            ->andWhere(['<','refund_time',$time])
            ->andWhere(['order_status'=>ConstantService::$order_status['RETURNED_PURCHASE']])
            ->andWhere(['is_delete'=>0])
            ->asArray()
            ->all();

        $id = array_column($order_model,'id');

        if(!empty($id)){
            $re = Order::updateAll(['order_status'=>ConstantService::$order_status['CLOSED']],['id'=>$id]);
            foreach ($id as $value){
                $ex = $this->_handleOrder($value);
            }

        }
        return true;
    }

    /**
     * 退款
     * @param $id
     * @return bool|string
     */
    private function _handleOrder($id){
        $order = Order::findOne(['id'=>$id]);
        $out_refund_no = CommonService::createOrderNo();
        //新增一个退款订单号
        $order->out_refund_no = $out_refund_no;
        $appid= \Yii::$app->params['wechat']['appid'];
        $mchid= \Yii::$app->params['wechat']['mchid'];
        $wechat_key= \Yii::$app->params['wechat']['key'];
        $total_fee = $order['order_money']*100;
        $refund_fee = $order['order_money']*100;
        $result = WechatService::applyRefund($appid,$mchid,$order['serial_no'],$out_refund_no,$total_fee,$refund_fee,$wechat_key);
        if($result === false || $result['result_code'] =='FAIL'){
            return '订单'.$id.'退款失败';
        }

        //将库存加回去  将成团表数量减去
        $Activity_attr = ActiveAttr::findOne(['id'=>$order['goods_attr_id']]);
        $inventory = $Activity_attr['inventory'];
        $Activity_attr->inventory = $inventory + $order['goods_num'];

        //加入redis存储库存
        $key = 'goods_'.$order['goods_attr_id'];
        //判断key是否存在
        $redis = RedisServer::initialization();
        $inventory_redis = $redis->getRedis($key);
        if($inventory_redis){
            //有redis
            $inventory_redis = $inventory_redis+$order['goods_num'];
            $redis->addRedis($key,$inventory_redis);

        }
        if($order['order_type'] == 1){
            //团购
            $group = Group::findOne(['id'=>$order['group_id']]);
            $group->current_group_num = $group['current_group_num'] - 1;
            $group->save();
        }

        if($Activity_attr->save()){
            $order->order_status = ConstantService::$order_status['CLOSED'];
            if($order->save()){
                return true;
            }
        }

    }

}